/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 微信管理，设置
 */
import React, { useState, useCallback, useMemo, useEffect } from "react";
import { connect } from "dva";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import { Row, Col, Button, Table, Popconfirm } from "antd";
import HelpAndService from "@/components/HelpAndService";
import QrCodeScanPage from "../components/QrCodeScanPage";
import SettingModal from "./components/SettingModal";
import UnbindRelationModal from "./components/UnbindRelationModal";
import Advertisement from "./Advertisement";
import CustomerService from "./CustomerService";
import CustomizedMenu from "./CustomizedMenu";
import Revenue from "./Revenue";
import MiniappPromotion from "./MiniappPromotion";
import styles from "../style.less";

const Setting = props => {
  const { dispatch, settingList = [], platformList, hasBind, loading } = props;
  const [showTitle, setShowTitle] = useState(false);
  const [title, setTitle] = useState("");
  const [open, setOpen] = useState(false); // 功能是否开启
  const [visible, setVisible] = useState(false);
  const [unbindModalVisible, setUnbindModalVisible] = useState(false);
  const [newAdd, setNewAdd] = useState(false);
  const [pageType, setPageType] = useState("pay");
  const [showRestPage, setShowRestPage] = useState(false);

  useEffect(
    () => {
      setShowTitle(hasBind);
      dispatch({
        type: "wxSettings/wxGetSettingList",
      });
    },
    [hasBind, dispatch]
  );

  const addNewConnect = useCallback(params => {
    setShowTitle(!params);
    setNewAdd(params);
  }, []);

  const onSettingClick = useCallback(
    ({ status, title, key }) => {
      if (key === "subscribe") {
        dispatch({
          type: "wxSettings/wxChangeSubscribeStatus",
          payload: {
            status: status == 1 ? 2 : 1,
          },
        }).then(() => {
          dispatch({
            type: "wxSettings/wxGetSettingList",
          });
        });
        return;
      }

      setPageType(key);
      setOpen(status == 1);

      if (key == "pay" || key == "score") {
        openModal(true);
        setTitle(`${title}设置`);
      } else {
        setShowRestPage(true);
      }
    },
    [openModal, dispatch]
  );

  // 关闭积分功能、关闭在线支付、关闭关注公众号功能
  const onCloseScore = useCallback(
    type => {
      const typeMap = {
        pay: "wxSettings/wxOnlinePay",
        score: "wxSettings/wxOpenScore",
        subscribe: "wxSettings/wxChangeSubscribeStatus",
      };
      const payload = {
        pay: {
          pay_status: 2,
        },
        score: {
          status: 2,
        },
        subscribe: {
          status: 2,
        },
      };

      dispatch({
        type: typeMap[type],
        payload: payload[type],
      }).then(() => {
        dispatch({
          type: "wxSettings/wxGetSettingList",
        });
      });
    },
    [dispatch]
  );

  const openModal = useCallback(_visible => {
    setVisible(_visible);
  }, []);

  const openUnbindModal = useCallback(_visible => {
    setUnbindModalVisible(_visible);
  }, []);

  const onGoBack = useCallback(
    () => {
      setShowRestPage(false);
      dispatch({
        type: "wxSettings/wxGetSettingList",
      });
    },
    [dispatch]
  );

  const columns = useMemo(
    () => [
      {
        title: "功能设置",
        dataIndex: "title",
        key: "key",
      },
      {
        title: "状态",
        dataIndex: "status",
        render: (_, record) => {
          const { key, status } = record;
          if (key === "pay" || key === "score" || key === "subscribe") {
            return status == 2 ? "已关闭" : "已开启";
          } else {
            return status == 2 ? "未设置" : "已设置";
          }
        },
      },
      {
        title: "说明",
        dataIndex: "info",
      },
      {
        title: "操作",
        width: 200,
        render: (_, record) => {
          const { status, key } = record;
          const text = status == 2 ? "开启" : "设置";

          if (key === "score") {
            return (
              <Row type="flex" gutter={[20, 0]}>
                {status == 1 && (
                  <Col>
                    <Popconfirm title="确定关闭积分功能？" onConfirm={() => onCloseScore(key)}>
                      <Button ghost type="danger">
                        关闭
                      </Button>
                    </Popconfirm>
                  </Col>
                )}
                <Col>
                  <Button type="primary" onClick={() => onSettingClick(record)}>
                    {text}
                  </Button>
                </Col>
              </Row>
            );
          }

          if (key === "pay") {
            if (status == 2) {
              return (
                <Button onClick={() => onSettingClick(record)} type="primary">
                  设置
                </Button>
              );
            } else {
              return (
                <Popconfirm title="确定关闭在线支付功能？" onConfirm={() => onCloseScore(key)}>
                  <Button ghost type="danger">
                    关闭
                  </Button>
                </Popconfirm>
              );
            }
          }

          if (key === "subscribe") {
            return status == 2 ? (
              <Button type="primary" onClick={() => onSettingClick(record)}>
                开启
              </Button>
            ) : (
              <Popconfirm title="确定关闭关注公众号功能？" onConfirm={() => onCloseScore(key)}>
                <Button ghost type="danger">
                  关闭
                </Button>
              </Popconfirm>
            );
          }

          return (
            <Button onClick={() => onSettingClick(record)} type="primary">
              设置
            </Button>
          );
        },
      },
    ],
    [onSettingClick, onCloseScore]
  );

  const RestPage = ({ goBack }) => {
    switch (pageType) {
      case "advertisement":
        return <Advertisement goBack={goBack} />;
      case "connect":
        return <CustomerService goBack={goBack} />;
      case "menu":
        return <CustomizedMenu goBack={goBack} />;
      case "revenue":
        return <Revenue goBack={goBack} />;
      case "promotion":
        return <MiniappPromotion goBack={goBack} />;
      default:
        return null;
    }
  };

  return (
    <PageHeaderLayout
      content={
        hasBind && showTitle ? (
          <div>
            <Row type="flex" justify="space-between" align="middle">
              <Col className={styles.overview}>
                <Row gutter={[10, 10]}>
                  <Col>功能设置适用于</Col>
                  <Col>
                    <span>
                      定制公众号：
                      <span className="title">
                        {(platformList.weixin && platformList.weixin.platformName) || "-"}
                      </span>
                    </span>
                    <span>
                      定制小程序：
                      <span className="title">
                        {(platformList.weixin_mini && platformList.weixin_mini.platformName) || "-"}
                      </span>
                    </span>
                  </Col>
                </Row>
              </Col>
              <Col>
                <Row type="flex" justify="end" gutter={[20, 0]}>
                  <Col>
                    <a onClick={() => addNewConnect(true)}>新增关联</a>
                  </Col>
                  <Col>
                    <a onClick={() => openUnbindModal(true)}>解除</a>
                  </Col>
                  <Col>
                    <HelpAndService />
                  </Col>
                </Row>
              </Col>
            </Row>
          </div>
        ) : (
          <h3>定制公众号/小程序的客户请使用微信扫码后使用</h3>
        )
      }
    >
      <QrCodeScanPage
        goBack={hasBind ? () => addNewConnect(false) : ""}
        changeBindRelation={newAdd}
      >
        <div className={styles.main}>
          {showRestPage ? (
            <RestPage goBack={onGoBack} />
          ) : (
            <>
              <Table
                rowKey="key"
                loading={loading}
                columns={columns}
                dataSource={settingList}
                pagination={false}
              />
              <SettingModal
                visible={visible}
                open={open}
                title={title}
                showModal={openModal}
                type={pageType}
              />
            </>
          )}
          <UnbindRelationModal visible={unbindModalVisible} showModal={openUnbindModal} />
        </div>
      </QrCodeScanPage>
    </PageHeaderLayout>
  );
};

export default connect(({ wxSettings, platform, loading }) => ({
  settingList: wxSettings.settingList,
  platformList: platform.platformList,
  hasBind: platform.hasBind,
  loading: loading.effects["wxSettings/wxGetSettingList"],
}))(Setting);
